package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.admin.entity.AdChannel;
import com.heima.admin.mapper.AdChannelMapper;
import com.heima.admin.service.IAdChannelService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dtos.PageResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.BeanHelper;
import com.heima.model.admin.dtos.ChannelDto;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * <p>
 * 频道信息表 服务实现类
 * </p>
 *
 * @author heima
 * @since 2021-03-11
 */
@Service
public class AdChannelServiceImpl extends ServiceImpl<AdChannelMapper, AdChannel> implements IAdChannelService {

    @Override
    public PageResult<ChannelDto> findByPage(ChannelDto channelDto) {

        //构建分页条件
        Page<AdChannel> page = new Page<>(channelDto.getPage(),channelDto.getSize());
        //构建查询条件 基于频道名称模糊查询
        String name = channelDto.getName();
        QueryWrapper<AdChannel> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotBlank(name)){
            // where name like '%java%'
            queryWrapper.lambda().like(AdChannel::getName,name);
            //queryWrapper.like("name",name);
        }
        //执行查询
        IPage<AdChannel> iPage = page(page, queryWrapper);
        List<AdChannel> records = iPage.getRecords();
        //封装查询结果
        if(CollectionUtils.isEmpty(records)){
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST,"频道列表数据不存在");
        }
        //将AdChannel结果集转为ChannelDto
        List<ChannelDto> channelDtoList = BeanHelper.copyWithCollection(records, ChannelDto.class);
        return new PageResult<ChannelDto>(channelDto.getPage(),channelDto.getSize(),iPage.getTotal(),channelDtoList);
    }

    @Override
    public void deleteById(Integer id) {
        //基于id查询频道数据，判断频道的状态是否有效
        AdChannel adChannel = getById(id);
        //获取频道状态
        Boolean status = adChannel.getStatus();
        if(status){
            //有效状态的频道，不能直接删除
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR,"有效状态的频道，不能直接删除");
        }
        //删除无效状态频道
        boolean b = removeById(id);
        if(!b){
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR,"删除频道失败");
        }
    }
}
